package util;

import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;

/**
 * @author wujiazhan
 * @className ByteArrUtil
 * @description 浮点数数组转字节数组工具类
 * @date 2021-06-02 20:14
 */
public class ConversionUtil {

    /**
     * 浮点数数组转字节数组
     * @param arr 输入的浮点数数组
     * @return 字节数组
     */
    public static byte[] asByteArray(double[] arr){
        if(null == arr ){
            return null;
        }
        return asByteBuffer(DoubleBuffer.wrap(arr)).array();
    }

    private static ByteBuffer asByteBuffer(DoubleBuffer input){
        if(null == input ){
            return null;
        }
        ByteBuffer buffer = ByteBuffer.allocate(input.capacity()* (Double.SIZE/8));
        while(input.hasRemaining()){
            buffer.putDouble(input.get());
        }
        return buffer;
    }


    /**
     * 字节数组转浮点数数组
     * @param bytes 输入的字节数组
     * @return 浮点数数组
     */
    public static double[] asDoubleArray(byte[] bytes){
        if(null == bytes ){
            return null;
        }
        DoubleBuffer buffer = ByteBuffer.wrap(bytes).asDoubleBuffer();
        double[] res = new double[buffer.remaining()];
        buffer.get(res);
        return res;
    }

    /**
     * 字节数组转浮点数
     * @param arr 字节数组
     * @return 浮点数
     */
    public static double bytesToDouble(byte[] arr) {
        long value = 0;
        for (int i = 0; i < 8; i++) {
            value |= ((long) (arr[i] & 0xff)) << (8 * i);
        }
        return Double.longBitsToDouble(value);
    }
}
